﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ImageProcessing;
using System.Drawing;

namespace Image_Processing_Website
{
    public partial class ImageUserControl : System.Web.UI.UserControl, ICallbackEventHandler
    {
        #region private members 

        private List<String> m_imageURLs = null;
        private String m_callbackResult = null;

        #endregion

        #region protected methods
        protected override void OnInit(EventArgs e)
        {
            m_imageURLs = new List<String>();
            m_imageURLs.Add(@"http://i.minus.com/ibzIMXKdIUiqZL.jpg");
            m_imageURLs.Add(@"http://i.minus.com/i8kMJZ3YvXNaK.jpg");
            m_imageURLs.Add(@"http://i.minus.com/iWj5GjCUsDyLa.jpg");
            m_imageURLs.Add(@"http://i.minus.com/ipFnPAltzV96v.jpg");
            m_imageURLs.Add(@"http://i.minus.com/ibvAHxLlUl8bMy.jpg");
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
             
            }
            // Creating the scripts which need to be called
            string clientScript = "function serverRequest(args, context){{ " + Page.ClientScript.GetCallbackEventReference(this, "args", "getResult", "context") + "; }} function getResult(result, context){{ eval(result); callServer(); }} function callServer(){setTimeout('serverRequest();', 5000);} callServer();";

            // Register the client script
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "ProcessingImageCallback", clientScript, true);

        }

        #endregion

        #region private methods 

    private String getRandomImage()
    {
        int randomIndex = (new Random()).Next(0, m_imageURLs.Count);
        string strReturn = @"<img src=  " + m_imageURLs[randomIndex] + " />";
        return strReturn;        
    }

    #endregion

        #region ICallbackEventHandler Members
    /// <summary>
    /// This method returns the result of a callback
    /// </summary>
    /// <returns>a string of the result of the callback</returns>
    public string GetCallbackResult()
    {
        return m_callbackResult;
    }

    /// <summary>
    /// This method processes the callback event
    /// </summary>
    /// <param name="eventArgument"></param>
    public void RaiseCallbackEvent(string eventArgument)
    {
        m_callbackResult = "document.getElementById('ProcessingImage').innerHTML = '" + this.getRandomImage() + "'";
    }
        #endregion

    }
}